<template>
  <div class="login">
    <!-- 登录 -->
    <div class="from">
      <PackFrom :inputArr="FromArr" :btn="butContent" :Errer="PromptError" @submit="submit" @input="synchronizationData">
        <template v-slot:automatic>
          <label class="label">
            <input type="checkbox" class="checkbox" ref="isChecked" @click="Checked">
            <span>自动登录</span>
          </label>
        </template>
      </PackFrom>
    </div>
  </div>
</template>

<script setup>
import {ref} from "vue"
import {useRouter} from "vue-router"
import {setWithExpiry,getWithExpiry} from "@/util/localStorage.js"
import {useUserStore} from "@/store/useUserStore.js"
import PackFrom from "./PackFrom.vue";


let FromArr = ref([
  {
    title: "学号",
    studentId: "",
    err: [
      {
        required: true,
        msg: "请输入学号"
      },{
        regular: "^\\d{9}$",
        msg: "学号必须是9位(必须是数字)"
      }
    ],
    corresponding: "studentId",
    type:"text"
    
  },
  {
    title: "密码",
    loginPwd: "",
    err: [
      {
        required: true,
        msg: "请输入密码"
      },{
        regular: "^\\S{6,10}$",
        msg: "任意字符6-10位(不能有空格等)"
      }
    ],
    corresponding: "loginPwd",
    type:"password"
  },
])


const butContent = "登录"
const PromptError = "请输入账号密码"
const store = useUserStore()
import { storeToRefs } from "pinia";
const isChecked = ref(null)
// 从仓库中结构数据
const {readUserInfo} = storeToRefs(store)
// 从仓库中解构方法
const {Login,getUserInfo} = store
// 路由
const router = useRouter()

// 同步数据
function synchronizationData(data){
  FromArr.value = data
}

// 登录时是否保存token
async function submit(data) {
  const res = await Login(data);
  // console.log(res);
  if(res.start === 1){
    FromArr.value.forEach(item => {
        item[item.corresponding] = ""
    })
  } else if(res.start === 0){
    if(isChecked.value.checked){
      // console.log("isChecked.value.checked",isChecked.value.checked,isChecked.value);
      setWithExpiry("token",res.data,7 * 24 * 60 * 60 * 1000)
    }
  }
}
// 自动登录
async function automatic(){
  if(getWithExpiry("token")){
    let item = getWithExpiry("token")
    sessionStorage.setItem("token",item.token)
    await getUserInfo()
    if(readUserInfo){
      router.push("home")
    }
  } else {
    return
  }
}
automatic()
</script>
<style scopde lang="less">
@import "@/styles/var.less";
.login {
  position: relative;
  width: 100%;
  height: 100%;
  .from {
    width: 80%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -60%);
  }
  .label{
    cursor: pointer;
  }
  .checkbox{
    width: 15px;
    height: 15px;
    vertical-align: middle;
  }

}
</style>